package service

import (
	"errors"
	"fmt"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
	"gin-luban-server/utils"
)
//@author: heyibo
//@function: CreateDeployBuild
//@description: 创建ci/cd树信息
//@param: build DeployBuild
//@return: err error, apply model.DeployBuild

func CreateDeployBuild(build model.DeployBuildHistory) (err error) {
	err = global.GVA_DB.Create(&build).Error
	return err
}

//@author: heyibo
//@function: UpdateDeployBuild
//@description: 更新应用、环境、服务器关联表
//@return: err error, build model.DeployBuild
func UpdateDeployBuild(build model.DeployBuildHistory) (err error) {
	err = global.GVA_DB.Where("id = ?", build.ID).First(&model.DeployApp{}).Updates(&build).Error
	return err
}

//@author: heyibo
//@function: GetDeployBuildList
//@description: 更新应用、环境、服务器关联表
//@return: err error, build model.DeployBuild

func GetDeployBuildList(info request.SearchDeployBuildParams) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.DeployBuildHistory{})
	var buildList []model.DeployBuildHistory
	err = db.Preload("DeployAppConfigure").Count(&total).Error
	if info.AppsName!= "" {
		db = db.Where("apps_name = ?", info.AppsName)
	}

	if info.AppsJobName != "" {
		db = db.Where("apps_job_name = ?", info.AppsJobName)
	}

	if info.DeployEnv != "" {
		db = db.Where("deploy_env = ?",info.DeployEnv)
	}
	// 发布类型 {正常发布|回滚发布}
	if info.DeployType != "" {
		db = db.Where("deploy_type= ?",info.DeployType)
	}

	if info.DeployStatus !="" {
		db = db.Where("deploy_status = ?",info.DeployStatus)
	}
	if err != nil {
		return err, buildList, total
	} else {
		db = db.Order("id desc").Limit(limit).Offset(offset)
		err = db.Find(&buildList).Error
	}
	return err, buildList, total
}


//@author: heyibo
//@function: GetAppBranchName
//@description: 获取分支列表
//@return: err error, branchList

func GetDeployAppBranchList(appName string)(err error,branchList []utils.GitlabBranchNameList)  {
	var gitLab utils.GitlabClient
	var DeployApp model.DeployApp
	var basic model.SysBasicConfigure
	err = global.GVA_DB.Model(&model.SysBasicConfigure{}).Where("purpose = ? AND status = ?","gitlab",1).First(&basic).Error
	if err != nil{
		return err,nil
	}
	err = global.GVA_DB.Model(&model.DeployApp{}).Where("apps_name = ? ",appName).First(&DeployApp).Error
	if err != nil {
		return err,nil
	}
	gitLab.UrlRepo = DeployApp.GitlabUrl
	gitLab.User = basic.BasicUser
	gitLab.Password = basic.BasicPasswd
	fmt.Println(gitLab)
    data,err := utils.GetDeployAppBranchList(&gitLab)
	if err == nil {
		branchList = data
	}else {
		return err,nil
	}
	return err,branchList
}


// 获取Tag列表
func GetAppGitRepoInfo(appName string)(err error,infoList utils.GitLabRepoInfo)  {
	var gitLab utils.GitlabClient
	var DeployApp model.DeployApp
	var basic model.SysBasicConfigure
	err = global.GVA_DB.Model(&model.SysBasicConfigure{}).Where("purpose = ? AND status = ?","gitlab",1).First(&basic).Error
	if err != nil{
		return err,infoList
	}
	err = global.GVA_DB.Model(&model.DeployApp{}).Where("apps_name = ? ",appName).First(&DeployApp).Error
	if err != nil {
		return err,infoList
	}
	gitLab.UrlRepo = DeployApp.GitlabUrl
	gitLab.User = basic.BasicUser
	gitLab.Password = basic.BasicPasswd
	fmt.Println(gitLab)
	data, err := utils.GetAppGitRepoInfo(&gitLab)
	if err == nil {
		infoList = data
	}else {
		return err,infoList
	}
	return err,infoList
}

//@author: heyibo
//@function: GetApplyDeployMap
//@description: 获取项目部署架构
//@return: err error, GetApplyDeployMapList

//func GetApplyDeployMapList(params request.ApplyDeployMapParams) (err error,deployMapList []model.CmdbServer) {
//    var applyVirtualList []model.VirtualCodeList
//	err = global.GVA_DB.Model(&model.DeployAppVirtual{}).Select("virtual_code").Where("apps_code = ? AND deploy_env = ?",params.AppsCode,params.DeployEnv).Scan(&applyVirtualList).Error
//	if err != nil {
//		return err,nil
//	}
//	err = global.GVA_DB.Model(&model.CmdbServer{}).Where("virtual_code IN ?",applyVirtualList).Find(&virtualList).Error
//	if err != nil {
//		return err,nil
//	}
//	return err,virtualList
//}


//@author: heyibo
//@function: GetApplyVirtualList
//@description: 获取应用部署服务器列表
//@return: err error, ApplyVirtualList

func GetApplyVirtualList(params request.ApplyVirtualParams) (err error,virtualList []model.CmdbServer) {
	var applyVirtualList []model.VirtualCodeList
	err = global.GVA_DB.Model(&model.DeployAppVirtual{}).Select("virtual_code").Where("apps_code = ? AND deploy_env = ?",params.AppsCode,params.DeployEnv).Scan(&applyVirtualList).Error
	var virtualArray []string
	for _, v :=range applyVirtualList {
		virtualArray= append(virtualArray, v.VirtualCode)
	}
	if err != nil {
		return err,nil
	}
	err = global.GVA_DB.Model(&model.CmdbServer{}).Where("virtual_code IN ?",virtualArray).Find(&virtualList).Error
	if err != nil {
		return err,nil
	}
	return err,virtualList
}



// jenkins 部署回调
func DeployNotify(jobName string, buildNumber string, buildStatus string, deployType string) (err error) {
	var buildInfo model.DeployBuildHistory
	// normal和restart在同一个jenkins job中
	if deployType == "" {
		normalOrRestartTypes := []string{"normal", "restart"}
		fmt.Println(normalOrRestartTypes, "----------")
		err = global.GVA_DB.Debug().Preload("DeployAppConfigure").Where("build_number = ? AND apps_job_name = ? AND deploy_type IN ?", buildNumber, jobName, normalOrRestartTypes).Last(&buildInfo).Error
	} else {
		// 回滚的job 有deployType 参数为 rollback
		err = global.GVA_DB.Preload("DeployAppConfigure").Where("build_number = ? AND apps_job_name = ? AND deploy_type = ?", buildNumber, jobName, deployType).Last(&buildInfo).Error
	}
	if err != nil {
		return errors.New(buildNumber + "数据记录中查询失败")
	}

	if buildStatus == "SUCCESS" ||  buildStatus == "success" {
		buildInfo.DeployStatus = "2"   // 部署成功
		var backupPath string
		// 判断是否前端
		if buildInfo.DeployAppConfigure.AppsType == "web" {
			backupPath ="dist.tar.gz"  // 前端写死
		} else {
			backupPath = buildInfo.DeployAppConfigure.PackageName
		}
		// 项目/环境/应用/版本/包名
		buildInfo.BackupPath = buildInfo.DeployAppConfigure.ProjectCode + "/" + buildInfo.DeployEnv + "/" + buildInfo.AppsName + "/" + buildInfo.Version + "/" + backupPath

		// 通过部署的机房 判断FTP下载包的地址
		if buildInfo.DeployAppConfigure.ServerIdc == "SAIC-ClOUD" {
			buildInfo.BackupHost = global.GVA_CONFIG.FTPPackage.SaicCloud
		} else if buildInfo.DeployAppConfigure.ServerIdc == "TELECOM" {
			buildInfo.BackupHost = global.GVA_CONFIG.FTPPackage.Telecom
		} else {
			buildInfo.BackupHost = global.GVA_CONFIG.FTPPackage.ShangKai9
		}

	} else {
		buildInfo.DeployStatus = "3"   // 部署失败
		buildInfo.Version = ""   		// 版本设置为空
	}
	global.GVA_DB.Save(&buildInfo)

	return err
}
